package yu.liu.personal.app.myapplication.ui.fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import yu.liu.personal.app.myapplication.R;
import yu.liu.personal.app.myapplication.components.PopupCollection;
import yu.liu.personal.app.myapplication.components.parts.FunctionBarAvgListPage;
import yu.liu.personal.app.myapplication.components.views.AnimatedExpandableListView;
import yu.liu.personal.app.myapplication.components.views.ComparePanelPopupWindow;
import yu.liu.personal.app.myapplication.components.views.FilterPanelPopupWindow;
import yu.liu.personal.app.myapplication.models.AVGItem;
import yu.liu.personal.app.myapplication.models.AVGList;
import yu.liu.personal.app.myapplication.models.AssistConstants;
import yu.liu.personal.app.myapplication.utils.DataReader;
import yu.liu.personal.app.myapplication.utils.adapters.AVGListAdapter;

/**
 * Created by Administrator on 2016/9/25.
 */

public class AVGListFragment extends BaseFragment {

    @BindView(R.id.exlvFragAvgList)
    AnimatedExpandableListView exlvFragAvgList;
    private AVGListAdapter adapterAVGList;
    private FunctionBarAvgListPage functionBar;

    // ------ Filter Function
    private FilterPanelPopupWindow filterPopWindow;
    private List<Boolean> typeCheckList;
    private List<Boolean> starCheckList;
    private List<Boolean> consumeCheckList;
    private PopupCollection.OnConfirmClickListener confirmClickListener;
    private PopupWindow.OnDismissListener onDismissListener;
    private boolean canPop = true;

    // ------ Compare Function
    private ComparePanelPopupWindow comparePopWindow;

    private AVGList avgList;
    private Handler functionHandler;

    private boolean isTop = true;

    @Override
    protected View loadViews(LayoutInflater inflater) {
        fragmentView = inflater.inflate(resManager
                .getResourceID("layout", "layout_fragment_avg_list"), null);
        ButterKnife.bind(this, fragmentView);
        functionBar = new FunctionBarAvgListPage(resContext);
        functionBar.initView(fragmentView, resManager
                .getResourceID("id", "boxFuncBarFragAvgList"));
        exlvFragAvgList.setGroupIndicator(null);
        exlvFragAvgList.setChildIndicator(null);
        exlvFragAvgList.setDivider(new ColorDrawable(0));
        exlvFragAvgList.setSelector(new ColorDrawable(0));
        return fragmentView;
    }

    @Override
    protected void loadMembers() {
        functionHandler = new FunctionHandler(this);
        functionBar.setFunctionHandler(functionHandler);
        avgList = DataReader.getListFromAssets(resContext, DataReader.AREA_CODE_CHS);
        adapterAVGList = new AVGListAdapter(resContext);
        Collections.sort(avgList.avglist);
        adapterAVGList.setAvgItems(avgList.avglist);
        exlvFragAvgList.setAdapter(adapterAVGList);
        exlvFragAvgList.setOnGroupClickListener(new ListGroupClickListener());
        exlvFragAvgList.setOnScrollListener(new ListTopOnScrollListener());
        exlvFragAvgList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        confirmClickListener = new FilterPopOnConfirmClickListener();
        onDismissListener = new FilterPopOnDismissListener();
    }

    @Override
    protected void postSetup() {
        adapterAVGList.notifyDataSetChanged();
    }

    @Override
    protected void updateViews() {

    }

    public boolean getListIsTop() {
        return isTop;
    }

    private class ListGroupClickListener
            implements ExpandableListView.OnGroupClickListener {

        @Override
        public boolean onGroupClick(ExpandableListView parent, View v,
                                    int groupPosition, long id) {
            if (exlvFragAvgList != null) {
                if(adapterAVGList.getCompareSelectStatus() == AVGListAdapter
                        .COMPARE_STATUS_IDLE) {
                    if (exlvFragAvgList.isGroupExpanded(groupPosition)) {
                        exlvFragAvgList.collapseGroupWithAnimation(groupPosition);
                    } else {
                        exlvFragAvgList.expandGroupWithAnimation(groupPosition);
                    }
                } else {
                    AVGItem result = adapterAVGList.selectOrUnselectGroupForComp
                            (groupPosition);
                    if(result == null) {
                        Toast.makeText(resContext, "无法选择多于三个对比对象...", Toast
                                .LENGTH_LONG).show();
                    }
                    adapterAVGList.notifyDataSetChanged();
                }
            }
            return true;
        }
    }

    private class ListTopOnScrollListener implements AbsListView.OnScrollListener {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount,
                             int totalItemCount) {
            if (firstVisibleItem == 0) {
                View firstVisibleItemView = exlvFragAvgList.getChildAt(0);
                if (firstVisibleItemView != null &&
                    firstVisibleItemView.getTop() == 0) {
//                    Log.d("EXLV", "<----滚动到顶部----->");
                    isTop = true;
                } else {
                    isTop = false;
                }
            } else {
                isTop = false;
            }
        }
    }

    private static class FunctionHandler extends Handler {
        private WeakReference<AVGListFragment> fragRef;

        FunctionHandler(AVGListFragment fragment) {
            fragRef = new WeakReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            AVGListFragment fragment = fragRef.get();
            switch (msg.what) {
                case FunctionBarAvgListPage.FUNC_FILTER:
                    // show filter dialog
                    if (fragment.canPop) {
                        fragment.filterPopWindow = new FilterPanelPopupWindow(fragment
                                .resContext);
                        fragment.filterPopWindow
                                .setTypeCheckedFlags(fragment.typeCheckList);
                        fragment.filterPopWindow
                                .setStarCheckedFlags(fragment.starCheckList);
                        fragment.filterPopWindow
                                .setConsumeCheckedFlags(fragment.consumeCheckList);
                        fragment.filterPopWindow.initWindow(fragment.functionBar
                                .getContentView(), fragment.resManager.getResourceID
                                ("layout", "layout_popwin_avg_list_func_filter"));
                        fragment.filterPopWindow
                                .setOnConfirmClickListener(fragment
                                        .confirmClickListener);
                        fragment.filterPopWindow.setOutsideTouchable(true);
                        fragment.filterPopWindow
                                .setOnDismissListener(fragment.onDismissListener);
                        fragment.filterPopWindow.showPopupWindow();
                    }
                    break;
                case FunctionBarAvgListPage.FUNC_SEARCH:
                    String condition = (String) msg.obj;
                    // search by condition
                    switch (condition) {
                        case "耐久最高":
                            // hp max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_HP);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "护盾最高":
                            // shield max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_SHIELD);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "装甲最高":
                            // armor max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_ARMOR);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "抵抗最高":
                            // resist max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_RESIST);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "火力最高":
                            // atk max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_ATK);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "侦察最高":
                            // scout max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_SCOUT);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "机动最高":
                            // spd max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_SPD);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "油耗最高":
                            // oil consume max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_OIL);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        case "弹耗最高":
                            // ammo consume max
                            fragment.adapterAVGList
                                    .findBest(AssistConstants.SEARCH_TYPE_AMMO);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                        default:
                            // normal search
                            fragment.adapterAVGList.find(condition);
                            fragment.adapterAVGList.notifyDataSetChanged();
                            break;
                    }
                    break;
                case FunctionBarAvgListPage.FUNC_COMPARE:
                    // start compare selection and change to reset btn
//                    Toast.makeText(fragment.resContext, "还在建设中...", Toast
//                            .LENGTH_LONG).show();
                    if (fragment.adapterAVGList.getCompareSelectStatus() ==
                        AVGListAdapter.COMPARE_STATUS_IDLE) {
                        fragment.adapterAVGList.enterSelectionMode();
                        fragment.functionBar.setCompareRunBtn(false);
                    } else {
                        fragment.adapterAVGList.quitSelectionMode();
                        fragment.functionBar.setCompareRunBtn(true);
                    }
                    fragment.adapterAVGList.notifyDataSetChanged();
                    break;
                case FunctionBarAvgListPage.FUNC_COMPARE_RUN:
                    // go for compare
                    if (fragment.adapterAVGList.getCompareSelectStatus() ==
                        AVGListAdapter.COMPARE_STATUS_AVAILABLE) {
                        // open up a popup window for compare
                        fragment.comparePopWindow = new ComparePanelPopupWindow
                                (fragment.resContext);
                        fragment.comparePopWindow.initWindow(fragment.functionBar
                                .getContentView(), fragment.resManager.getResourceID
                                ("layout", "layout_popwin_avg_list_func_compare"));
                        fragment.comparePopWindow.setFocusable(true);
                        fragment.comparePopWindow.setCompareItems(fragment
                                .adapterAVGList.getSelectItems());
                        fragment.comparePopWindow.showPopupWindow();
                        fragment.comparePopWindow.updateViews();
                    } else if(fragment.adapterAVGList.getCompareSelectCounter() < 2) {
                        Toast.makeText(fragment.resContext, "请选择两个或三个比较对象...",
                                Toast.LENGTH_LONG).show();
                    }
                default:
                    break;
            }
        }
    }

    private class FilterPopOnConfirmClickListener implements PopupCollection
            .OnConfirmClickListener {
        @Override
        public void onConfirm() {
            if (filterPopWindow != null) {
                typeCheckList = filterPopWindow.getTypeCheckedFlags();
                starCheckList = filterPopWindow.getStarCheckedFlags();
                consumeCheckList = filterPopWindow.getConsumeCheckedFlags();
                // apply the filter
            }
            adapterAVGList
                    .filterTheList(typeCheckList, starCheckList, consumeCheckList);
            adapterAVGList.notifyDataSetChanged();
        }
    }

    private class FilterPopOnDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            canPop = false;
            Thread counter = new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                        canPop = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            counter.start();
        }
    }

//    private class ComparePopOnDismissListener implements PopupWindow.OnDismissListener {
//
//        @Override
//        public void onDismiss() {
//
//        }
//    }
}
